package DOM;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ModifyExistingXML {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String xmlFileName=ModifyExistingXML.class.getResource("../resources/staff.xml").getPath();
		System.out.println(xmlFileName);
		
		try{
			DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
			Document doc=docBuilder.parse(xmlFileName);
			
			Node root=doc.getDocumentElement();
			
			NodeList nNodes=root.getChildNodes();
			
			System.out.println(nNodes.getLength());
			for(int i=0;i<nNodes.getLength();i++){
				
				Node nNode=nNodes.item(i);
				if(nNode.getNodeType()==Node.ELEMENT_NODE){
					Element eElement=(Element)nNode;
					
					System.out.println(eElement.getAttribute("id"));
					eElement.setAttribute("id", eElement.getAttribute("id")+"_");
				}
			}
			
			
			// write the content into xml file
			TransformerFactory transformerFactory=TransformerFactory.newInstance();
			Transformer transformer=transformerFactory.newTransformer();
			DOMSource source=new DOMSource(doc);
			StreamResult result=new StreamResult(new File(xmlFileName));
			transformer.transform(source, result);
			
		
		}
		catch(SAXException e){
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
